package cj.web.admin.controllers;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.DateUtils;
import cj.utils.ExportExcel;
import cj.web.admin.dao.GameDAO;
import cj.web.admin.dao.ReportsDAO;
import cj.web.admin.domain.Game;
import cj.web.admin.domain.Permit;
import cj.web.constants.MemuEnum;
import cj.web.constants.PermitStatusEnum;
import cj.web.login.controllers.BaseController;

@Path("reports")
public class ReportsController extends BaseController {

	private static Logger logger = Logger.getLogger(ReportsController.class.getName());

	@Autowired
	private ReportsDAO reportsDao;
	@Autowired
	private GameDAO gameDao;
	
	
	//-------------------------------------报名统计(学校)
	@Get("showBMTJZ")
	public String showBMTJZ(Model model) {
		model.add("MemuEnum", MemuEnum.reportsbmtjz);
		List<Game> objs = gameDao.queryAll();
        model.add("gameObjs",objs);
        model.add("endAt", DateUtils.getMinusTime(DateUtils.getNowTime(), DateUtils.DATE_FULL_STR, -1));
		model.add("startAt", DateUtils.getMinusMonth(DateUtils.getNowTime(), DateUtils.DATE_FULL_STR, 1));
		
		return "/views/reports/bmtjzList.vm";
	}
	
	@Post("getBMTJZList")
	public String queryBMTJZList(@Param("gameId") int gameId,@Param("startAt") String startAt,@Param("endAt") String endAt) {
		JSONObject jo = new JSONObject();
		List<Map> objs = reportsDao.queryReportsBMTJZ(gameId, startAt, endAt);
		jo.put("data", objs);
		jo.put("recordsTotal", 0);
		jo.put("recordsFiltered", 0);
		return "@"+jo.toString();
	}
	
	//-------------------------------------报名统计(区域)
	@Get("showBMTJR")
	public String showBMTJR(Model model) {
		model.add("MemuEnum", MemuEnum.reportsbmtjr);
		List<Game> objs = gameDao.queryAll();
        model.add("gameObjs",objs);
        model.add("endAt", DateUtils.getMinusTime(DateUtils.getNowTime(), DateUtils.DATE_FULL_STR, -1));
		model.add("startAt", DateUtils.getMinusMonth(DateUtils.getNowTime(), DateUtils.DATE_FULL_STR, 1));
		
		return "/views/reports/bmtjrList.vm";
	}
	
	@Post("getBMTJRList")
	public String queryBMTJRList(@Param("gameId") int gameId,@Param("startAt") String startAt,@Param("endAt") String endAt) {
		JSONObject jo = new JSONObject();
		List<Map> objs = reportsDao.queryReportsBMTJR(gameId, startAt, endAt);
		jo.put("data", objs);
		jo.put("recordsTotal", 0);
		jo.put("recordsFiltered", 0);
		return "@"+jo.toString();
	}
	
	//-------------------------------------销量统计
	@Get("showXLTJ")
	public String showXLTJ(Model model) {
		model.add("MemuEnum", MemuEnum.reportsxltj);
		model.add("endAt", DateUtils.getMinusTime(DateUtils.getNowTime(), DateUtils.DATE_FULL_STR, -1));
		model.add("startAt", DateUtils.getMinusMonth(DateUtils.getNowTime(), DateUtils.DATE_FULL_STR, 1));
		
		return "/views/reports/xltjList.vm";
	}
	
	@Post("getXLTJList")
	public String queryXLTJList(@Param("startAt") String startAt,@Param("endAt") String endAt) {
		JSONObject jo = new JSONObject();
		List<Map> objs = reportsDao.queryReportsXLTJ(startAt, endAt);
		
		int sumCount = 0;
		for(Map rep:objs){
			int sellcount = rep.get("sellcount")==null?0:Integer.parseInt(rep.get("sellcount").toString());
			sumCount = sumCount+sellcount;
			rep.put("sellcount", sellcount);
		}
		Map rep = new HashMap();
		rep.put("name", "总计");
		rep.put("sellcount", sumCount);
		objs.add(rep);
		
		jo.put("data", objs);
		jo.put("recordsTotal", 0);
		jo.put("recordsFiltered", 0);
		return "@"+jo.toString();
	}
	
	//---------------------------------------统计跨区参赛人数
	@Get("showBMCrossTJ")
	public String showBMCrossTJ(Model model) {
		model.add("MemuEnum", MemuEnum.reportsbmtjcross);
		model.add("endAt", DateUtils.getMinusTime(DateUtils.getNowTime(), DateUtils.DATE_FULL_STR, -1));
		model.add("startAt", DateUtils.getMinusMonth(DateUtils.getNowTime(), DateUtils.DATE_FULL_STR, 1));
		List<Game> objs = gameDao.queryAll();
        model.add("gameObjs",objs);
		return "/views/reports/bmcrosstjList.vm";
	}
	
	@Post("getBMCrossTJList")
	public String queryBMCrossTJList(@Param("startAt") String startAt,@Param("endAt") String endAt,
			@Param("gameId") int gameId) {
		JSONObject jo = new JSONObject();
		List<Map> objs = reportsDao.queryReportsBMCrossTJ(gameId, startAt, endAt);
		
		jo.put("data", objs);
		jo.put("recordsTotal", 0);
		jo.put("recordsFiltered", 0);
		return "@"+jo.toString();
	}
	
	//---------------------------------------统计每个区的报名人数
	@Get("showBMAreaTJ")
	public String showBMAreaTJ(Model model) {
		model.add("MemuEnum", MemuEnum.reportsbmtjarea);
		model.add("endAt", DateUtils.getMinusTime(DateUtils.getNowTime(), DateUtils.DATE_FULL_STR, -1));
		model.add("startAt", DateUtils.getMinusMonth(DateUtils.getNowTime(), DateUtils.DATE_FULL_STR, 1));
		List<Game> objs = gameDao.queryAll();
        model.add("gameObjs",objs);
		return "/views/reports/bmareatjList.vm";
	}
	
	@Post("getBMAreaTJList")
	public String queryBMAreaTJList(@Param("startAt") String startAt,@Param("endAt") String endAt,
			@Param("gameId") int gameId) {
		JSONObject jo = new JSONObject();
		List<Map> objs = reportsDao.queryReportsBMAreaTJ(gameId, startAt, endAt);
		
		jo.put("data", objs);
		jo.put("recordsTotal", 0);
		jo.put("recordsFiltered", 0);
		return "@"+jo.toString();
	}
	
	//---------------------------------------统计学校获奖人数
	@Get("showBMSchoolScoreTJ")
	public String showBMSchoolScoreTJ(Model model) {
		model.add("MemuEnum", MemuEnum.reportsbmtjschoolscore);
		List<Game> objs = gameDao.queryAll();
        model.add("gameObjs",objs);
		return "/views/reports/bmschoolscoretjList.vm";
	}
	
	@Post("getBMSchoolScoreTJList")
	public String queryBMSchoolScoreTJList(@Param("gameId") int gameId) {
		JSONObject jo = new JSONObject();
		List<Map> objs = reportsDao.queryReportsBMSchoolScoreTJ(gameId);
		
		jo.put("data", objs);
		jo.put("recordsTotal", 0);
		jo.put("recordsFiltered", 0);
		return "@"+jo.toString();
	}
	
	//---------------------------------------指导老师的获奖人数
	@Get("showBMSchoolTeacherTJ")
	public String showBMSchoolTeacherTJ(Model model) {
		model.add("MemuEnum", MemuEnum.reportsbmtjschoolteacher);
		List<Game> objs = gameDao.queryAll();
        model.add("gameObjs",objs);
		return "/views/reports/bmschoolteachertjList.vm";
	}
	
	@Post("getBMSchoolTeacherTJList")
	public String queryBMSchoolTeacherTJList(@Param("gameId") int gameId,@Param("start") int start,@Param("length") int length) {
		JSONObject jo = new JSONObject();
		
		List<Map> objs = reportsDao.queryReportsBMSchoolTeacherTJ(gameId,start,length);
		int size = reportsDao.queryReportsBMSchoolTeacherTJSize(gameId);
		
		jo.put("data", objs);
		jo.put("draw", 0);
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@"+jo.toString();
	}
	
	//---------------------------------------区的获奖排名
	@Get("showBMAreaScoreTJ")
	public String showBMAreaScoreTJ(Model model) {
		model.add("MemuEnum", MemuEnum.reportsbmtjareascore);
		List<Game> objs = gameDao.queryAll();
        model.add("gameObjs",objs);
		return "/views/reports/bmareascoretjList.vm";
	}
	
	@Post("getBMAreaScoreTJList")
	public String queryBMAreaScoreTJList(@Param("gameId") int gameId) {
		JSONObject jo = new JSONObject();
		
		List<Map> objs = reportsDao.queryReportsBMAreaScoreTJ(gameId);
		
		jo.put("data", objs);
		jo.put("recordsTotal", 0);
		jo.put("recordsFiltered", 0);
		return "@"+jo.toString();
	}
	
	//--------------------------导出
	/**
	 * 导出by gameId start length type
	 * @param gameId
	 * @param start
	 * @param length
	 * @param type		
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Get("output")
	public void output(@Param("gameId") int gameId,@Param("startAt") String startAt,@Param("endAt") String endAt,
			@Param("type") String type, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setContentType("application/vnd.ms-excel"); // 生成提示信息
		response.setHeader("content-disposition", "attachment;filename="
				+ type + DateUtils.getNowTime(DateUtils.DATE_FULL_STR1)
				+ ".xls");
		OutputStream fOut = response.getOutputStream();

		ExportExcel<Map> ex = new ExportExcel<Map>();
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();

		List<Map> dataset = null;

		String[] headers = null ;
		String[] fields = null ;
		// 信息Export
		if(type.equals("showBMTJZ")){
			headers = new String[] {"学校名称","总数量","报名成功","未付款","已使用"};
			fields = new String[] {"name", "num", "paidCount", "notPayCount", "used"};
			dataset = reportsDao.queryReportsBMTJZ(gameId, startAt, endAt);
		}else if (type.equals("showBMTJR")){
			headers = new String[] {"区域名称","总数量","报名成功","未付款","已使用"};
			fields = new String[] {"name", "num", "paidCount", "notPayCount", "used"};
			dataset = reportsDao.queryReportsBMTJR(gameId, startAt, endAt);
		}else if (type.equals("showBMCrossTJ")){
			headers = new String[] {"报名区域","学生读书区域","报名人数"};
			fields = new String[] {"areaName", "area", "count"};
			dataset = reportsDao.queryReportsBMCrossTJ(gameId, startAt, endAt);
		}else if (type.equals("showBMAreaTJ")){
			headers = new String[] {"报名区域","报名人数"};
			fields = new String[] {"areaName", "count"};
			dataset = reportsDao.queryReportsBMAreaTJ(gameId, startAt, endAt);
		}

		ex.exportExcelMore(workbook,type, headers, fields, dataset, DateUtils.DATE_FULL_STR);
		
		try {
			//关闭工作薄
			workbook.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		}

		fOut.flush();
		fOut.close();
	}
	
	/**
	 * 导出by gameId type
	 * @param gameId
	 * @param type
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Get("outputScore")
	public void outputScore(@Param("gameId") int gameId,@Param("type") String type, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setContentType("application/vnd.ms-excel"); // 生成提示信息
		response.setHeader("content-disposition", "attachment;filename="
				+ type + DateUtils.getNowTime(DateUtils.DATE_FULL_STR1)
				+ ".xls");
		OutputStream fOut = response.getOutputStream();

		ExportExcel<Map> ex = new ExportExcel<Map>();
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();

		List<Map> dataset = null;

		String[] headers = null ;
		String[] fields = null ;
		// 信息Export
		if(type.equals("showBMAreaScoreTJ")){
			headers = new String[] {"区域", "总人数", "一等奖", "二等奖", "三等奖", "特等奖"};
			fields = new String[] {"area", "totalNum", "firstPrize", "secondPrize", "thridPrize", "specialAward"};
			dataset = reportsDao.queryReportsBMAreaScoreTJ(gameId);
		}else if (type.equals("showBMSchoolScoreTJ")){
			headers = new String[] {"区域","学校","总人数","一等奖","二等奖","三等奖","特等奖"};
			fields = new String[] {"area", "school", "totalNum", "firstPrize", "secondPrize", "thridPrize", "specialAward"};
			dataset = reportsDao.queryReportsBMSchoolScoreTJ(gameId);
		}else if (type.equals("showBMSchoolTeacherTJ")){
			headers = new String[] {"区域","学校","教师","总人数","一等奖","二等奖","三等奖","特等奖"};
			fields = new String[] {"area", "school", "teacher", "totalNum", "firstPrize", "secondPrize", "thridPrize", "specialAward"};
			dataset = reportsDao.queryReportsBMSchoolTeacherTJ(gameId,0,99999);
		}

		ex.exportExcelMore(workbook,type, headers, fields, dataset, DateUtils.DATE_FULL_STR);
		
		try {
			//关闭工作薄
			workbook.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		}

		fOut.flush();
		fOut.close();
	}
	
	/**
	 * 导出by startAt endAt
	 * @param startAt
	 * @param endAt
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Get("outputSC")
	public void outputSC(@Param("startAt") String startAt,@Param("endAt") String endAt, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		response.setContentType("application/vnd.ms-excel"); // 生成提示信息
		response.setHeader("content-disposition", "attachment;filename=outputSC"
				+ DateUtils.getNowTime(DateUtils.DATE_FULL_STR1)
				+ ".xls");
		OutputStream fOut = response.getOutputStream();

		ExportExcel<Map> ex = new ExportExcel<Map>();
		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();

		List<Map> dataset = null;

		String[] headers = {"书名","销售数量"} ;
		String[] fields = {"name", "sellcount"};
		
		dataset = reportsDao.queryReportsXLTJ(startAt, endAt);
		
		int sumCount = 0;
		for(Map rep:dataset){
			int sellcount = rep.get("sellcount")==null?0:Integer.parseInt(rep.get("sellcount").toString());
			sumCount = sumCount+sellcount;
			rep.put("sellcount", sellcount);
		}
		Map rep = new HashMap();
		rep.put("name", "总计");
		rep.put("sellcount", sumCount);
		dataset.add(rep);

		ex.exportExcelMore(workbook,"sc", headers, fields, dataset, DateUtils.DATE_FULL_STR);
		
		try {
			//关闭工作薄
			workbook.write(fOut);
		} catch (IOException e) {
			e.printStackTrace();
		}

		fOut.flush();
		fOut.close();
	}
}